/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package action.retail;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.validator.annotations.VisitorFieldValidator;
import database.AuthenticationDAO;
import java.util.Map;
import model.Customer;
import model.Memberaccount;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;

/**
 *
 * @author Thai Ha Cong
 */
@Namespace("/Member")
public class LoginAction extends ActionSupport implements ModelDriven<Memberaccount> {

    private Memberaccount memberaccount = new Memberaccount();

    public LoginAction() {
    }

    public Memberaccount getMemberaccount() {
        return memberaccount;
    }

    public void setMemberaccount(Memberaccount memberaccount) {
        this.memberaccount = memberaccount;
    }

//    @Override
//    public void validate() {
//        if (this.username.length() == 0) {
//            addFieldError("username", "Username is required.");
//        } else if (this.username.length() < 6) {
//            addFieldError("username", "Username is too short.");
//        }
//
//        if (this.password.length() == 0) {
//            addFieldError("password", "Password is required.");
//        }
//    }
    @Override
    public String execute() throws Exception {
        return SUCCESS;
    }

    @Action(value = "login", results = {
        @Result(name = "success", location = "/index.jsp"),
        @Result(name = "input", location = "/member/login.jsp")
    })
    public String login() throws Exception {
        String result;

        AuthenticationDAO adao = new AuthenticationDAO();

        if (adao.checkLogin(memberaccount)) {
            Customer customer = adao.getCustomerFromUsername(memberaccount.getUsername());
            Map session = ActionContext.getContext().getSession();
            session.put("username", memberaccount.getUsername());
            System.out.println(customer.getFirstName());
            session.put("currentCustomer", customer);
//            System.out.println(session.get("username"));
            
            result = SUCCESS;
        } else {
            addActionError("Login Failed. Wrong username or password.");
            result = INPUT;
        }

        return result;
    }

    @Override
    @VisitorFieldValidator(message = "", appendPrefix = false)
    public Memberaccount getModel() {
        return memberaccount;
    }
}